package com.cino.demos.controller.file;

import cn.hutool.core.io.FileUtil;
import com.cino.demos.common.Result;
import com.cino.demos.common.utils.AliOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;


@RestController
@RequestMapping("/files")
@Slf4j
@CrossOrigin
public class File1Controller {

    @Autowired
    private AliOSSUtil aliOSSUtil;

    // 当前的项目的根目录/files/
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Value("${fileBaseUrl}")
    private String fileBaseUrl;

    /**
     * 文件上传
     */
    @PostMapping("/uploadByBytes")
    public Result uploadByBytes(MultipartFile file) {
        // 定义文件的唯一标识
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        // 拼接完整的文件存储路径
        String realFilePath = filePath + fileName;
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            FileUtil.writeBytes(file.getBytes(), realFilePath);
        } catch (IOException e) {
            log.error("文件上传错误", e);
        }
        String url = fileBaseUrl + "/files/download/" + fileName;
        return Result.success(url);
    }

    /*
    文件上传
     */
    @PostMapping("/uploadTransferTo")
    public Result upload(MultipartFile file) throws IOException {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //构建新的文件名
        String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //将文件保存在服务器端 E://images/目录下
        file.transferTo(new File("E:/images/"+newFileName));
        return Result.success();
    }


    /**
     * aliyunOSS文件上传
     */
    @PostMapping("/aliOssUpload")
    public Result OssUpload(MultipartFile file) throws IOException {
        log.info("文件上传,文件名：{}",file.getOriginalFilename());
        String url = aliOSSUtil.upload(file);
        return Result.success(url);
    }

    /**
     * 文件下载
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        OutputStream os;
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, String.valueOf(StandardCharsets.UTF_8)));
        response.setContentType("application/octet-stream");
        try {
            // 拼接完整的文件存储路径
            String realFilePath = filePath + fileName;
            // 通过文件的存储路径拿到文件流
            byte[] bytes = FileUtil.readBytes(realFilePath);
            os = response.getOutputStream();
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error("文件下载错误", e);
        }
    }



}
